<?php
namespace Api\SA;

use S\Exception;
use S\Http;

/**
 * Class Util
 * @package Api\Openapi
 * @description openapi服务请求工具类
 */
class Util {

    const DEV_URL = "https://sa.beebank.com/";  //请求基础url
    const PRODUCT_URL = "http://sa.i.beebank.com/";
    const ERR_CODE_SUCCESS = "2000000";  //成功响应码

    private $code;
    private $message;

    /**
     * 发送请求
     *
     * @param $uri
     * @param array $params
     * @param int $timeout default 10
     *
     * @return mixed
     * @throws \S\Exception
     */
    public function request($uri, array $params, $timeout = 10){
        $url = (\Core\Env::isProductEnv() ? self::PRODUCT_URL : self::DEV_URL);
        $options = array(
            'timeout' => $timeout,
        );

        $http = new Http($url);
        $response = $http->request(Http::METHOD_POST, $uri, $params, $options);

        if (!$response) {
            throw new Exception("empty response from sa", 5200001);
        }
        $result = json_decode($response, true);
        if (empty($result)) {
            \S\Log\Logger::getInstance()->error(array($response));
            throw new Exception("error format response from sa", 5200002);
        }
        if (self::ERR_CODE_SUCCESS != $result["retcode"]) {
            $this->code = $result['retcode'];
            $this->message = $result['msg'];
            return false;
        }else{
            $this->code = $result['retcode'];
            $this->message = $result['msg'];
            unset($result['retcode']);
            unset($result['msg']);
            return $result;
        }
    }

    public function getCode(){
        return $this->code;
    }

    public function getMessage(){
        return $this->message;
    }

} 